﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
using System.Collections.Generic;
using Microsoft.Office.Server.UserProfiles;
using System.Collections;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{

    //http://www.designkindle.com/2011/10/07/build-icons/
    //http://webdesignledger.com/freebies/50-amazing-free-icon-sets
    //http://speckyboy.com/2012/12/17/top-50-free-icon-sets-from-2012/

    public partial class Personnel_Action_Form : LayoutsPageBase
    {
        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        decimal PrevgrdTotal = 0;
        decimal PresgrdTotal = 0;

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string PARequestNo;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;

        public static string ActionClassifications;

        public static string ActionDetails;

        public static string Nationalities;
        public static string ActionTypes;
        public static string Divisions;
        public static string Designations;

        public static string lstGuid;
        public string camlQry;
        public SPQuery qry;
        public static string Mode;
        public static string TaskItemID;
        public static string submittedfor;
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList;
        public static string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string refID;
        public static int PAItemID;

        public static bool Binding = true;

        string[] buttonVisibilty = new string[5];

        private static SPListItemCollection oItemsColl = null;
        private static SPListItem oItems = null;

        public static string ActionType;

        private int isDuplicateNo;
        private bool isDuplicateClassName = false;

        List<string> strListSpecification = new List<string>();

        public string evtHandler;

        #endregion


        public Personnel_Action_Form()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Personnel Action Forms";
            TaskLstName = "Personnel Action Tasks";
            CmntsLstName = "Personnel Action Comments";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";

            ActionClassifications = "Personnel Action Classifications";
            Nationalities = "Nationalities";
            ActionTypes = "Personnel Action Types";
            ActionDetails = "Personnel Action Details";
            Divisions = "Divisions";
            Designations = "Designations";

        }


        protected void Page_Load(object sender, EventArgs e)
        {

            txtName.Attributes.Add("onChange", "isValidity();");
            txtEmployeeNo.Attributes.Add("onChange", "isValid();");
            txtFathersName.Attributes.Add("onChange", "isValids();");

            if (!IsPostBack)
            {
                Mode = Request.QueryString["Mode"];
                refID = Request.QueryString["RefID"]; // From Dashboard.
                TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);
                // Bind Values in All DropDown Lists
                SetValuesInDropdowns();

                if (Mode == "Edit" || Mode == "View")
                {
                    //singlerow();
                    FormApprovalLoad(); HideRowCommand(); if (Mode == "View") InvisibleButtons();
                }
                else if (Mode == "New")
                {
                    FirstLoadofForm();
                    GetClassifications();  // After creating row,then bind values in gridview dropdown list Classification.
                }
                else
                {
                    pnlFullForm.Visible = false;
                    pnlAccessDenied.Visible = true;
                    lblAccessDeniedMsg.Visible = true;
                    lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                }
            }

            ActionType = ddlActionType.SelectedItem.Text;

            //if (Binding)
            //    GetPersonnelActionDetails();
        }


        private void HideRowCommand()
        {
            if (gvSalaryInfo.Rows.Count > 0)
            {
                gvSalaryInfo.HeaderRow.Cells[4].Visible = false;
                foreach (GridViewRow gvr in gvSalaryInfo.Rows)
                {
                    gvr.Cells[4].Visible = false;
                }
                gvSalaryInfo.FooterRow.Cells[4].Visible = false;
            }
        }

        private bool GetPersonnelActionDetails()
        {
            bool ckUser = false;
            if (Mode == "New")
            {
                if (ddlActionType.SelectedIndex > 1 || ddlActionType.SelectedItem.Text != "Appointment")
                {

                    Binding = false;
                    try
                    {
                        PickerEntity pe = (PickerEntity)pplActUser.Entities[0];
                        string ActUser = pe.DisplayText;

                        camlQry = "<Where><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + ActUser + "</Value></Eq></Where>";
                        qry = new SPQuery();
                        qry.Query = camlQry;
                        oItems = obj.GetSPListItem(SiteURL, "Personnel Action Forms", qry);
                        if (oItems != null)
                        {
                            ckUser = true;
                            SetValuesToControls(oItems);
                            camlQry = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + Convert.ToString(oItems["Title"]) + "</Value></Eq></Where>";
                            SetStatusAndClassification(ddlActionType.SelectedItem.Text);
                        }

                    }
                    catch (Exception)
                    {

                    }

                }

            }
            return ckUser;
        }

        /// <summary>
        /// To check whether the Form is in Document Types master list or not.
        /// Also get the document prefix and starting number of the form
        /// Otherwise the user gets Access Denied
        /// </summary>
        public void FirstLoadofForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string[] getDocRefNumber = demandVoucherclass.getRefNum(SiteURL, DocumentTypesList, MainLstName);

                    if (!string.IsNullOrEmpty(getDocRefNumber[0]) && !string.IsNullOrEmpty(getDocRefNumber[1]))
                    {
                        singlerow();
                        dtReqDate.SelectedDate = DateTime.Today.Date;
                        if (gvSalaryInfo.Rows.Count == 1)
                        {
                            gvSalaryInfo.Rows[0].Cells[4].Enabled = false;
                        }
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Access Denied, DocPrefix or Starting Number column value in Document Types Master list is missing. Contact administrator.";
                    }
                });
            }
            catch (Exception ex)
            {
                //GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::FirstLoadofForm", "Exception in catch block", ex.Message);
            }
        }

        public void singlerow()
        {
            try
            {
                if (ViewState["CurrentTable"] == null)
                {
                    DataTable dt = new DataTable();
                    DataRow dr = null;
                    dt.Columns.Add(new System.Data.DataColumn("NewRow", typeof(string)));
                    dr = dt.NewRow();
                    dr["NewRow"] = "1";
                    dt.Rows.Add(dr);
                    gvSalaryInfo.DataSource = dt;
                    gvSalaryInfo.DataBind();
                    ViewState["CurrentTable"] = dt;
                }
            }
            catch (Exception)
            {

            }
        }


        #region Bind In DropDown Controls

        private void SetValuesInDropdowns()
        {
            try
            {
                GetNationalities();
                GetActionTypes();

                GetDesignations();
                GetDivisions();

            }
            catch (Exception)
            {

                throw;
            }
        }

        private void GetNationalities()
        {
            try
            {
                BindInDropDown(Nationalities, ddlNationality);
                ddlNationality.Items.Insert(0, "Select");
            }
            catch (Exception)
            {

            }
        }

        private void GetActionTypes()
        {
            try
            {
                BindInDropDown(ActionTypes, ddlActionType);
                ddlActionType.Items.Insert(0, "Select");
            }
            catch (Exception)
            {

            }
        }

        private void GetClassifications()
        {
            try
            {
                DropDownList ddlSpecification = gvSalaryInfo.Rows[0].FindControl("ddlSpecification") as DropDownList;
                BindInDropDown(ActionClassifications, ddlSpecification);
                ddlSpecification.Items.Insert(0, "Select");

            }
            catch (Exception)
            {

            }


        }

        private void GetDesignations()
        {
            try
            {
                //DropDownList ddlPrevDesignation = gvSalaryInfo.Rows[0].FindControl("ddlPrevDesignation") as DropDownList;
                //DropDownList ddlPresDesignation = gvSalaryInfo.Rows[0].FindControl("ddlPresDesignation") as DropDownList;
                BindInDropDown(Designations, ddlDesigPrev);
                ddlDesigPrev.Items.Insert(0, "Select");
                BindInDropDown(Designations, ddlDesigPres);
                ddlDesigPres.Items.Insert(0, "Select");
            }
            catch (Exception)
            {

            }


        }

        private void GetDivisions()
        {
            try
            {
                //DropDownList ddlPrevDivision = gvSalaryInfo.Rows[0].FindControl("ddlPrevDivision") as DropDownList;
                //DropDownList ddlPresDivision = gvSalaryInfo.Rows[0].FindControl("ddlPresDivision") as DropDownList;

                BindInDropDown(Divisions, ddlDivPrev);
                ddlDivPrev.Items.Insert(0, "Select");
                BindInDropDown(Divisions, ddlDivPres);
                ddlDivPres.Items.Insert(0, "Select");

            }
            catch (Exception)
            {

            }


        }

        #endregion

        /// <summary>
        /// GridView row databound event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvSalaryInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            //if (e.Row.RowType == DataControlRowType.Footer)
            //{
            //    Label lblPreviousTtl = (Label)e.Row.FindControl("lblPreviousTtl");
            //    Label lblPresentTtl = (Label)e.Row.FindControl("lblPresentTtl");
            //    lblPreviousTtl.Text = PrevgrdTotal.ToString("c");
            //    lblPresentTtl.Text = PresgrdTotal.ToString("c");

            //}

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int rowIndex = Convert.ToInt32(e.Row.DataItemIndex);
                evtHandler = "updateValue(this," + rowIndex + ",1)";
                TextBox txtRate = (TextBox)e.Row.FindControl("txtPrevious");
                txtRate.Attributes.Add("onkeyup", evtHandler);   //onkeyup  //onchange
                TextBox txtQuantity = (TextBox)e.Row.FindControl("txtPresent");
                txtQuantity.Attributes.Add("onkeyup", evtHandler);
            }


        }


        /// <summary>
        /// Grid view row command
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvSalaryInfo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);
            Guid siteId = SPContext.Current.Site.ID;
            Guid webId = SPContext.Current.Web.ID;
            if (e.CommandName == "ReDelete")
            {
                DataTable dt2 = GetGridViewDataSource();
                dt2.Rows[id].Delete();
                gvSalaryInfo.DataSource = dt2;
                gvSalaryInfo.DataBind();
                SetGridViewValues(dt2);
                if (gvSalaryInfo.Rows.Count == 1)
                {
                    gvSalaryInfo.Rows[0].Cells[4].Enabled = false;
                }
                SetFooterValues();
                HideGVPrevious();
            }
            if (gvSalaryInfo.Rows.Count == 0)
            {
                ViewState["CurrentTable"] = null;
                singlerow();
                GetClassifications();
                if (gvSalaryInfo.Rows.Count == 1)
                {
                    gvSalaryInfo.Rows[0].Cells[4].Enabled = false;
                }
            }

        }


        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                Label lblPreviousTtls = (Label)e.Row.FindControl("lblPreviousTtl");
                Label lblPresentTtls = (Label)e.Row.FindControl("lblPresentTtl");
                lblPreviousTtls.Text = PrevgrdTotal.ToString();//.ToString("c");
                lblPresentTtls.Text = PresgrdTotal.ToString();//.ToString("c");
            }
        }



        private decimal g(GridViewRowEventArgs e)
        {
            decimal rowTotal;
            try
            {
                TextBox txtPrev = (TextBox)e.Row.FindControl("txtPrevious");
                rowTotal = Convert.ToDecimal(txtPrev.Text);
            }
            catch (Exception)
            {
                rowTotal = 0;
            }
            return rowTotal;
        }

        /// <summary>
        /// add rows for DV expenses
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Bbtnadd_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt2 = new DataTable();
                dt2 = GetGridViewDataSource();
                DataRow drEmptyRow = dt2.NewRow();
                dt2.Rows.Add(drEmptyRow);
                gvSalaryInfo.DataSource = dt2;
                gvSalaryInfo.DataBind();
                SetGridViewValues(dt2);

                Label lblTotPrev = (Label)gvSalaryInfo.FooterRow.FindControl("lblPreviousTtl");
                Label lblTotPres = (Label)gvSalaryInfo.FooterRow.FindControl("lblPresentTtl");

                lblTotPrev.Text = Convert.ToString(PrevgrdTotal);
                lblTotPres.Text = Convert.ToString(PresgrdTotal);

                CkDuplication();
                HideGVPrevious();
            }
            catch (Exception ex)
            {
                //exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::Bbtnadd_Click", "Exception in catch block", ex.Message);
            }

        }

        /// <summary>
        /// Assign datasource to gridview 
        /// </summary>
        /// <returns></returns>

        private DataTable GetGridViewDataSource()
        {
            DataTable dt2 = new DataTable();
            try
            {
                dt2.Columns.Add("Classification", typeof(string));
                dt2.Columns.Add("Previous", typeof(string));
                dt2.Columns.Add("Present", typeof(string));

                if (gvSalaryInfo.Rows.Count > 0)
                {
                    SPFieldLookupValue ofldlook = null;
                    for (int i = 0; i < gvSalaryInfo.Rows.Count; i++)
                    {
                        DropDownList ddlClass = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
                        DataRow dr1 = dt2.NewRow();
                        if (ddlClass.SelectedValue != "Select")
                        {
                            ofldlook = new SPFieldLookupValue(ddlClass.SelectedValue);
                            dr1["Classification"] = ofldlook.LookupId;
                        }
                        TextBox txtPrevious = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPrevious");
                        dr1["Previous"] = txtPrevious.Text;

                        if (!string.IsNullOrEmpty(txtPrevious.Text))
                            PrevgrdTotal = PrevgrdTotal + Convert.ToDecimal(txtPrevious.Text);

                        TextBox txtPresent = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPresent");

                        dr1["Present"] = txtPresent.Text;
                        if (!string.IsNullOrEmpty(txtPresent.Text))
                            PresgrdTotal = PresgrdTotal + Convert.ToDecimal(txtPresent.Text);
                        dt2.Rows.Add(dr1);

                    }

                }
            }
            catch (Exception ex)
            {
                //exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::GetGridViewDataSource", "Exception in catch block", ex.Message);
            }
            return dt2;
        }

        /// <summary>
        /// set values to Grid view
        /// </summary>
        /// <param name="dt2"></param>


        private void SetGridViewValues(DataTable dt2)
        {
            DataRow drGetRow;
            SPFieldLookupValue ofldlook = null;

            decimal rowTotal;

            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                drGetRow = dt2.Rows[i];

                DropDownList ddlClass = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
                ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Classification"]));
                BindInDropDown(ActionClassifications, ddlClass);
                ddlClass.Items.Insert(0, "Select");

                if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["Classification"])))
                {
                    ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Classification"]));
                    ddlClass.Items.FindByValue(Convert.ToString(ofldlook.LookupId)).Selected = true;
                }

                TextBox txtPrevious = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPrevious");
                TextBox txtPresent = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPresent");

                txtPrevious.Text = Convert.ToString(drGetRow["Previous"]);
                txtPresent.Text = Convert.ToString(drGetRow["Present"]);

            }

        }


        #region "Old Gridview binding"

        ///// <summary>
        ///// Assign datasource to gridview 
        ///// </summary>
        ///// <returns></returns>

        //private DataTable GetGridViewDataSource()
        //{
        //    DataTable dt2 = new DataTable();
        //    try
        //    {
        //        dt2.Columns.Add("Classification", typeof(string));
        //        dt2.Columns.Add("Previous", typeof(string));
        //        dt2.Columns.Add("Present", typeof(string));

        //        if (gvSalaryInfo.Rows.Count > 0)
        //        {
        //            SPFieldLookupValue ofldlook = null;
        //            for (int i = 0; i < gvSalaryInfo.Rows.Count; i++)
        //            {
        //                DropDownList ddlClass = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
        //                DropDownList ddlPrevDes = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPrevDesignation");
        //                DropDownList ddlPresDes = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPresDesignation");
        //                DropDownList ddlPrevDiv = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPrevDivision");
        //                DropDownList ddlPresDiv = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPresDivision");

        //                DataRow dr1 = dt2.NewRow();
        //                ofldlook = new SPFieldLookupValue(ddlClass.SelectedValue);
        //                dr1["Classification"] = ofldlook.LookupId;

        //                if (ddlClass.SelectedItem.Text == "Division")
        //                {
        //                    ofldlook = new SPFieldLookupValue(ddlPrevDiv.SelectedValue);
        //                    dr1["Previous"] = ofldlook.LookupId;
        //                    ofldlook = new SPFieldLookupValue(ddlPresDiv.SelectedValue);
        //                    dr1["Present"] = ofldlook.LookupId;
        //                }
        //                else if (ddlClass.SelectedItem.Text == "Designation")
        //                {
        //                    ofldlook = new SPFieldLookupValue(ddlPrevDes.SelectedValue);
        //                    dr1["Previous"] = ofldlook.LookupId;
        //                    ofldlook = new SPFieldLookupValue(ddlPresDes.SelectedValue);
        //                    dr1["Present"] = ofldlook.LookupId;
        //                }
        //                else
        //                {
        //                    TextBox txtPrevious = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPrevious");
        //                    dr1["Previous"] = txtPrevious.Text;
        //                    PrevgrdTotal = PrevgrdTotal + Convert.ToDecimal(txtPrevious.Text);

        //                    TextBox txtPresent = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPresent");
        //                    dr1["Present"] = txtPresent.Text;
        //                    PresgrdTotal = PresgrdTotal + Convert.ToDecimal(txtPresent.Text);
        //                }

        //                dt2.Rows.Add(dr1);

        //            }

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        //exceptionHandler.GenerateExceptionLog("Trig_AMJ_AMG_Forms:: Demand_Voucher_Form::GetGridViewDataSource", "Exception in catch block", ex.Message);
        //    }
        //    return dt2;
        //}


        ///// <summary>
        ///// set values to Grid view
        ///// </summary>
        ///// <param name="dt2"></param>


        //private void SetGridViewValues(DataTable dt2)
        //{
        //    DataRow drGetRow;
        //    SPFieldLookupValue ofldlook = null;

        //    decimal rowTotal;

        //    for (int i = 0; i < dt2.Rows.Count; i++)
        //    {
        //        drGetRow = dt2.Rows[i];

        //        DropDownList ddlClass = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
        //        DropDownList ddlPrevDes = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPrevDesignation");
        //        DropDownList ddlPresDes = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPresDesignation");
        //        DropDownList ddlPrevDiv = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPrevDivision");
        //        DropDownList ddlPresDiv = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlPresDivision");
        //        TextBox txtPrevious = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPrevious");
        //        TextBox txtPresent = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPresent");



        //        BindInDropDown(ActionClassifications, ddlClass);
        //        BindInDropDown(Designations, ddlPrevDes); BindInDropDown(Designations, ddlPresDes);
        //        BindInDropDown(Divisions, ddlPrevDiv); BindInDropDown(Divisions, ddlPresDiv);


        //        txtPrevious.Text = Convert.ToString(drGetRow["Present"]);

        //        ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Classification"]));

        //        if (!string.IsNullOrEmpty(Convert.ToString(drGetRow["Classification"])))
        //        {
        //            ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Classification"]));
        //            ddlClass.Items.FindByValue(Convert.ToString(ofldlook.LookupId)).Selected = true;

        //            if (ddlClass.SelectedItem.Text == "Designation")
        //            {
        //                txtPrevious.Text = ""; txtPresent.Text = "";
        //                txtPrevious.Visible = false; txtPresent.Visible = false;

        //                ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Previous"]));
        //                ddlPrevDes.Visible = true;
        //                ddlPrevDes.Items.FindByValue(Convert.ToString(ofldlook.LookupId)).Selected = true;
        //                ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Present"]));
        //                ddlPresDes.Visible = true;
        //                ddlPresDes.Items.FindByValue(Convert.ToString(ofldlook.LookupId)).Selected = true;
        //            }
        //            else if (ddlClass.SelectedItem.Text == "Division")
        //            {
        //                txtPrevious.Text = ""; txtPresent.Text = "";
        //                txtPrevious.Visible = false; txtPresent.Visible = false;

        //                ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Previous"]));
        //                ddlPrevDiv.Visible = true;
        //                ddlPrevDiv.Items.FindByValue(Convert.ToString(ofldlook.LookupId)).Selected = true;
        //                ofldlook = new SPFieldLookupValue(Convert.ToString(drGetRow["Present"]));
        //                ddlPresDiv.Visible = true;
        //                ddlPresDiv.Items.FindByValue(Convert.ToString(ofldlook.LookupId)).Selected = true;

        //            }
        //            else
        //            {
        //                txtPrevious.Text = Convert.ToString(drGetRow["Previous"]);
        //                txtPresent.Text = Convert.ToString(drGetRow["Present"]);

        //            }
        //        }

        //    }

        //}

        #endregion


        protected void gvSalaryInfo_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            TextBox txtPrevious = gvSalaryInfo.Rows[0].FindControl("txtPrevious") as TextBox;
            DropDownList ddlSpecification = gvSalaryInfo.Rows[0].FindControl("ddlSpecification") as DropDownList;

            DropDownList ddlPrevDesignation = gvSalaryInfo.Rows[0].FindControl("ddlPrevDesignation") as DropDownList;
            DropDownList ddlPrevDivision = gvSalaryInfo.Rows[0].FindControl("ddlPrevDivision") as DropDownList;

            if (ddlSpecification.SelectedItem.Text == "Designation")
            {
                txtPrevious.Visible = false;
                ddlPrevDesignation.Visible = true;
                ddlPrevDivision.Visible = false;

            }
            else if (ddlSpecification.SelectedItem.Text == "Division")
            {
                txtPrevious.Visible = false;
                ddlPrevDesignation.Visible = false;
                ddlPrevDivision.Visible = true;
            }
            else
            {
                txtPrevious.Visible = true;
                ddlPrevDesignation.Visible = false;
                ddlPrevDivision.Visible = false;
            }
        }


        protected void ddlSpecification_Selectedindexchanged(object sender, EventArgs e)
        {


            int j = 0;

            //foreach (GridViewRow gr in gvSalaryInfo.Rows)
            //{
            //    DropDownList ddlcn = gr.FindControl("ddlSpecification") as DropDownList;
            //    strListSpecification.Add(ddlcn.SelectedValue);
            //}

            if (gvSalaryInfo.Rows.Count > 0)
            {
                if (CkDuplication() <= 1)
                {
                    isDuplicateClassName = true;
                }
                else
                {
                    //nationality.Text = ""; qatarID.Text = ""; expireDt.ClearSelection();
                    ClientScript.RegisterClientScriptBlock(GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);
                }

            }

            SetFooterValues();


            //Check if there are two or more same courseName in the List

            //foreach (string cls in strListSpecification)
            //{
            //    j = 0;
            //    for (int i = 0; i < strListSpecification.Count; i++)
            //    {
            //        if (cls == strListSpecification[i])
            //        {
            //            j++;
            //            if (j > 1)
            //            {
            //                isDuplicateClassName = true;
            //                ClientScript.RegisterClientScriptBlock(GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);
            //            }
            //        }
            //    }
            //}
        }

        private void SetFooterValues()
        {
            foreach (GridViewRow gr in gvSalaryInfo.Rows)
            {
                TextBox previous = gr.FindControl("txtPrevious") as TextBox;
                TextBox present = gr.FindControl("txtPresent") as TextBox;

                if (!string.IsNullOrEmpty(previous.Text))
                    PrevgrdTotal = PrevgrdTotal + Convert.ToDecimal(previous.Text);
                if (!string.IsNullOrEmpty(present.Text))
                    PresgrdTotal = PresgrdTotal + Convert.ToDecimal(present.Text);
            }

            Label previousTtl = (Label)gvSalaryInfo.FooterRow.FindControl("lblPreviousTtl");
            Label presentTtl = (Label)gvSalaryInfo.FooterRow.FindControl("lblPresentTtl");

            previousTtl.Text = Convert.ToString(PrevgrdTotal);
            presentTtl.Text = Convert.ToString(PresgrdTotal);
        }

        private int CkDuplication()
        {

            for (int i = 0; i < gvSalaryInfo.Rows.Count; i++)
            {
                DropDownList ddlSpecify = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");
                if (isDuplicateNo > 1)
                {
                    break;
                }
                else
                {
                    isDuplicateNo = 0;
                    for (int j = 0; j < gvSalaryInfo.Rows.Count; j++)
                    {

                        DropDownList ddlSpecification = (DropDownList)gvSalaryInfo.Rows[j].FindControl("ddlSpecification");
                        if (ddlSpecification.SelectedItem.Text.Contains(ddlSpecify.SelectedItem.Text))
                            isDuplicateNo++;
                        if (isDuplicateNo > 1)
                        {
                            isDuplicateClassName = true;

                            TextBox previous = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPrevious");
                            TextBox present = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPresent");
                            previous.Text = ""; present.Text = "";
                            previous.ReadOnly = true;
                            present.ReadOnly = true;
                            ScriptManager.RegisterClientScriptBlock(this, GetType(), "Duplication", "alert('Duplicate records are not allowed');", true);
                            break;
                        }
                        if (!isDuplicateClassName)
                        {
                            TextBox previous = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPrevious");
                            TextBox present = (TextBox)gvSalaryInfo.Rows[j].FindControl("txtPresent");

                            previous.ReadOnly = false;
                            present.ReadOnly = false;
                        }
                    }
                }

            }

            return isDuplicateNo;
        }


        protected void ddlActionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (pplActUser.Entities.Count > 0)
                {

                    if (ActionType == "Appointment")
                        pnlDiv.Visible = false;
                    else
                        pnlDiv.Visible = true;


                    if (ActionType == "Others")
                        txtOthers.Visible = true;
                    else
                        txtOthers.Visible = false;

                    if (ActionType != "Select")
                    {
                        if (ActionType != "Appointment")
                        {
                            if (GetPersonnelActionDetails())
                            {
                                Disable_Previous();
                                SetFooterValues();
                                HideGVPrevious();
                            }
                            else
                            {
                                pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('User not exist in list, you do not request the form!');</script>"));
                            }
                        }
                        else
                        {
                            HideGVPrevious();
                            CkUserInPersonnelActionForm();
                            EnableForAppointment();
                        }
                    }
                    else
                    {
                        pnlDiv.Visible = false;
                        EnableForAppointment();
                    }
                }
                else
                {
                    pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert(' Please enter the valid user!');</script>"));
                    pplActUser.Entities.Clear();
                }
            }
            catch (Exception ex)
            {
                
            }
            

        }

        private void HideGVPrevious()
        {
            try
            {
                for (int i = 0; i < gvSalaryInfo.Rows.Count; i++)
                {
                    if (ActionType != "Appointment")
                    {
                        TextBox txtPrev = (TextBox)gvSalaryInfo.Rows[i].Cells[2].FindControl("txtPrevious");
                        if (!string.IsNullOrEmpty(txtPrev.Text))
                            txtPrev.ReadOnly = true;
                        else
                            txtPrev.ReadOnly = false;
                    }
                    else
                    {
                        //TextBox txtPrev = (TextBox)gvSalaryInfo.Rows[i].Cells[2].FindControl("txtPrevious");                
                    }
                }
            }
            catch (Exception ex)
            {
                
              
            }
            

        }

        private void CkUserInPersonnelActionForm()
        {
            try
            {
                SPListItem oItem = null;

                PickerEntity pr = (PickerEntity)pplActUser.Entities[0];
                camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + pr.DisplayText + "</Value></Eq><Neq>" +
                    "<FieldRef Name=\"Document_x0020_Status\" /><Value Type=\"Text\">Rejected</Value></Neq></And></Where>";
                oItem = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (oItem != null)
                {
                    pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('User already exist in!');</script>"));
                    pplActUser.Entities.Clear();
                }
            }
            catch (Exception ex)
            { 
              
            }
            
           


        }


        private void Disable_Previous()
        {
            ddlDesigPrev.Enabled = false;
            ddlDivPrev.Enabled = false;

            foreach (GridViewRow gvr in gvSalaryInfo.Rows)
            {
                TextBox txtPrevious = gvr.FindControl("txtPrevious") as TextBox;
                txtPrevious.ReadOnly = true;
            }
        }

        private void EnableForAppointment()
        {
            try
            {

            
            txtName.Text = ""; txtName.ReadOnly = false;

            ddlNationality.Items.Clear();

            BindInDropDown(Nationalities, ddlNationality);
            ddlNationality.Items.Insert(0, "Select");
            ddlNationality.Enabled = true;

            ddlDesigPrev.Enabled = true;

            txtEmployeeNo.Text = ""; txtEmployeeNo.ReadOnly = false;
            dtDOB.ClearSelection(); dtDOB.Enabled = true;
            ddlMaritalStatus.Enabled = true;
            txtFathersName.Text = ""; txtFathersName.ReadOnly = false;
            txtNoDependant.Text = ""; txtNoDependant.ReadOnly = false;
            txtAddress.Text = ""; txtAddress.ReadOnly = false;
            txtTelNo.Text = ""; txtTelNo.ReadOnly = false;
            txtPassportNo.Text = ""; txtPassportNo.ReadOnly = false;
            dtPassValidity.ClearSelection(); dtPassValidity.Enabled = true;
            dtDOE.ClearSelection(); dtDOE.Enabled = true;
            txtQadarID.Text = ""; txtQadarID.ReadOnly = false;
            dtValofResPermit.ClearSelection(); dtValofResPermit.Enabled = true;

            gvSalaryInfo.DataSource = null; gvSalaryInfo.DataBind();
            ViewState["CurrentTable"] = null;
            singlerow();
            if (gvSalaryInfo.Rows.Count == 1)
            {
                gvSalaryInfo.Rows[0].Cells[4].Enabled = false;
            }
            GetClassifications();
            gvSalaryInfo.Visible = true;
            }
            catch (Exception ex)
            {

            }

        }


        //protected void ddlSpecification_selectedindexchanged(object sender, EventArgs e)
        //{
        //    DropDownList ddlSpecification = new DropDownList();
        //    DropDownList ddlPrevDesignation = new DropDownList(); DropDownList ddlPresDesignation = new DropDownList();
        //    DropDownList ddlPrevDivision = new DropDownList(); DropDownList ddlPresDivision = new DropDownList();

        //    TextBox txtPrevious = new TextBox();
        //    TextBox txtPresent = new TextBox();


        //    foreach (GridViewRow row in gvSalaryInfo.Rows)
        //    {
        //        ddlSpecification = (DropDownList)row.FindControl("ddlSpecification");

        //        ddlPrevDesignation = (DropDownList)row.FindControl("ddlPrevDesignation");
        //        ddlPresDesignation = (DropDownList)row.FindControl("ddlPresDesignation");
        //        ddlPrevDivision = (DropDownList)row.FindControl("ddlPrevDivision");
        //        ddlPresDivision = (DropDownList)row.FindControl("ddlPresDivision");

        //        txtPrevious = (TextBox)row.FindControl("txtPrevious"); txtPresent = (TextBox)row.FindControl("txtPresent");

        //        if (ddlSpecification != null)
        //        {
        //            if (ddlSpecification.SelectedItem.Text == "Designation")
        //            {
        //                txtPrevious.Visible = false; txtPresent.Visible = false;
        //                ddlPrevDesignation.Visible = true; ddlPresDesignation.Visible = true;
        //                ddlPrevDivision.Visible = false; ddlPresDivision.Visible = false;
        //            }

        //            else if (ddlSpecification.SelectedItem.Text == "Division")
        //            {
        //                txtPrevious.Visible = false; txtPresent.Visible = false;
        //                ddlPrevDesignation.Visible = false; ddlPresDesignation.Visible = false;
        //                ddlPrevDivision.Visible = true; ddlPresDivision.Visible = true;
        //            }
        //            else
        //            {
        //                txtPrevious.Visible = true; txtPresent.Visible = true;
        //                ddlPrevDesignation.Visible = false; ddlPresDesignation.Visible = false;
        //                ddlPrevDivision.Visible = false; ddlPresDivision.Visible = false;
        //            }
        //        }


        //    }
        //}


        private void BindInDropDown(string SourceListName, DropDownList ddlCntrls)
        {
            try
            {
                ddlCntrls.ClearSelection();
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        camlQry = "<Where><IsNotNull><FieldRef Name=\"Title\" /></IsNotNull></Where>";
                        SPList oList = oWeb.Lists.TryGetList(SourceListName);

                        if (oList != null)
                        {
                            ddlCntrls.DataSource = oList.Items.GetDataTable();
                            ddlCntrls.DataTextField = "Title";
                            ddlCntrls.DataValueField = "ID";
                            ddlCntrls.DataBind();
                        }

                    }
                }
            }
            catch (Exception ex)
            {
               
            }
            
            
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (Request.QueryString["Mode"] == "Edit")
                {
                    string formID = null;
                    string refNo = Request.QueryString["RefID"];
                    string taskItemID = Request.QueryString["TaskItemID"];
                    string Approver = SPContext.Current.Web.CurrentUser.LoginName;

                    if (GetSendbackStatus())
                    {
                        if (CheckServersideValidation())
                        {
                            SPLongOperation lop = new SPLongOperation(this.Page);
                            lop.LeadingHTML = "<DIV><H4>Personnel Action Clearance form approval is in progress</H4></DIV>";
                            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                            lop.Begin();
                            obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                            TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, null, false, 2, null, ddlDivPres.SelectedItem.Text, null);
                            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                        }
                    }
                    else
                    {

                        lblError.Visible = true; lblError.Text = "Can't be send back. User is not available";
                    }

                }
                else if (Request.QueryString["Mode"] == "New")
                {
                    SaveFormDetails();
                    ClientScript.RegisterClientScriptBlock(GetType(), "Record Saved", "window.close", true);
                }
            }
        }

        public bool GetSendbackStatus()
        {
            bool status = true;
            if (rtbSendBack.Checked)
            {
                SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]), lblActReqNo.Text, rtbSendBack, rtbForward, lblError);
                if (ofldUser == null)
                {
                    status = false;
                }
            }
            return status;
        }

        /// <summary>
        /// Check people editor validations
        /// </summary>
        /// <returns></returns>

        public bool CheckServersideValidation()
        {
            bool rval = true;
            if (rtbForwardOthers.Checked)
            {
                if (pplcnt.Accounts.Count > 0)
                {
                    rval = true;
                }
                else
                {
                    rval = false;
                    lblError.Text = "Please enter the user name to forward";
                }
            }
            return rval;
        }


        /// <summary>
        /// Save Form details 
        /// Add Items in Main List
        /// Add Items in Task List
        /// Add Items in Comments List
        /// Add Attachment to Attachment Library
        /// </summary>

        private void SaveFormDetails()
        {
            SPLongOperation lop = new SPLongOperation(this.Page);
            lop.LeadingHTML = "<DIV><H4>Personnel Action Clearance form submission is in progress...</H4></DIV>";
            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
            lop.Begin();

            string taskItemID = Request.QueryString["TaskItemID"];
            string Approver = SPContext.Current.Web.CurrentUser.LoginName;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    obj.AutoNoGeneration(MainLstName, DocumentTypesList, lblActReqNo, SiteURL);
                    PARequestNo = Convert.ToString(lblActReqNo.Text).Trim();
                    if (PARequestNo.Contains(DateTime.Now.Year.ToString()))
                    {
                        lstGuid = obj.AddPersonnelAction_Items(SiteURL, MainLstName, TaskLstName, CmntsLstName, AttLibName, upfile, WorkflowConfigList, pplcnt,
                            lblActReqNo.Text, dtReqDate.SelectedDate.Date, txtName.Text, ddlNationality.SelectedItem.Text, txtEmployeeNo.Text,
                            dtDOB.SelectedDate.Date, ddlMaritalStatus.SelectedItem.Text, txtFathersName.Text, txtNoDependant.Text, txtAddress.Text, txtTelNo.Text,
                            txtPassportNo.Text, dtPassValidity.SelectedDate.Date, dtDOE.SelectedDate.Date, txtQadarID.Text, dtValofResPermit.SelectedDate.Date,
                            ddlActionType.SelectedItem.Text, txtOthers.Text, CurrentUser, ddlDesigPres.SelectedItem.Text, ddlDivPres.SelectedItem.Text,
                            pplActUser.CommaSeparatedAccounts, TxtComments.Text);
                        SetActionDetails();

                    }
                    else
                    {
                        lblError.Text = "Master list details not in Doecument Types"; lblError.ForeColor = System.Drawing.Color.Red;
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "SaveFormDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

        }

        private void SetActionDetails()
        {
            //SetActionDetails("Designation", ddlDesigPrev, ddlDesigPres, "PreviousDesignation", "PresentDesignation");
            //SetActionDetails("Division", ddlDivPrev, ddlDivPres, "PreviousDivision", "PresentDivision");

            SetActionDetails(ddlDesigPrev, ddlDesigPres, ddlDivPrev, ddlDivPres);

            foreach (GridViewRow gr in gvSalaryInfo.Rows)
            {
                DropDownList ddlClass = gr.FindControl("ddlSpecification") as DropDownList;
                TextBox txtPrevious = gr.FindControl("txtPrevious") as TextBox;
                TextBox txtPresent = gr.FindControl("txtPresent") as TextBox;
                SetActionDetails(ddlClass, txtPrevious.Text, txtPresent.Text);
            }
        }

        private void SetActionDetails(DropDownList prevDes, DropDownList presDes, DropDownList prevDiv, DropDownList presDiv)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                SPFieldLookupValue fldPrev = null; SPFieldLookupValue fldPres = null;
                string referenceNo = lblActReqNo.Text;
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList oList = oWeb.Lists.TryGetList(ActionDetails);
                        if (oList != null)
                        {
                            SPQuery oEmptyQuery = new SPQuery();
                            oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                            SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                            SPListItem oItem = oItemColl.Add();
                            oItem["Title"] = referenceNo;

                            fldPrev = new SPFieldLookupValue(prevDes.SelectedValue);
                            oItem["PreviousDesignation"] = fldPrev.LookupId;

                            fldPres = new SPFieldLookupValue(presDes.SelectedValue);
                            oItem["PresentDesignation"] = fldPres.LookupId;

                            string subUser = pplActUser.CommaSeparatedAccounts;
                            //SPUser user = oWeb.EnsureUser(subUser);
                            SPUser User = oWeb.EnsureUser(subUser);//oWeb.SiteUsers[user.Name];
                            SPFieldUserValue SubmittedFor = new SPFieldUserValue(oWeb, User.ID, User.Name);
                            oItem["SubmittedFor"] = SubmittedFor;

                            if (prevDiv.SelectedValue != "Select")
                            {
                                fldPrev = new SPFieldLookupValue(prevDiv.SelectedValue);
                                oItem["PreviousDivision"] = fldPrev.LookupId;
                            }

                            fldPres = new SPFieldLookupValue(presDiv.SelectedValue);
                            oItem["PresentDivision"] = fldPres.LookupId;

                            oItem["ActionType"] = ddlActionType.SelectedItem.Text;

                            oWeb.AllowUnsafeUpdates = true;
                            oItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }


        private void SetActionDetails(DropDownList specification, string previous, string present)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                string referenceNo = lblActReqNo.Text;
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList oList = oWeb.Lists.TryGetList(ActionDetails);
                        if (oList != null)
                        {
                            SPQuery oEmptyQuery = new SPQuery();
                            oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                            SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                            SPListItem oItem = oItemColl.Add();
                            oItem["Title"] = Convert.ToString(referenceNo);

                            string subUser = pplActUser.CommaSeparatedAccounts;
                            //SPUser user = oWeb.EnsureUser(subUser);
                            SPUser User = oWeb.EnsureUser(subUser); //oWeb.SiteUsers[user.Name];
                            SPFieldUserValue SubmittedFor = new SPFieldUserValue(oWeb, User.ID, User.Name);
                            oItem["SubmittedFor"] = SubmittedFor;

                            SPFieldLookupValue fldSpecification = new SPFieldLookupValue(specification.SelectedValue);

                            oItem["Specification"] = fldSpecification.LookupId;
                            oItem["Previous"] = Convert.ToString(previous);
                            oItem["Present"] = Convert.ToString(present);
                            oItem["ActionType"] = ddlActionType.SelectedItem.Text;
                            oWeb.AllowUnsafeUpdates = true;
                            oItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }


        protected void btnApprove_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;
                if (GetSendbackStatus())
                {
                    if (CheckServersideValidation())
                    {
                        SPLongOperation lop = new SPLongOperation(this.Page);
                        lop.LeadingHTML = "<DIV><H4>Personnel Action Clearance form approval is in progress</H4></DIV>";
                        lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                        lop.Begin();
                        if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                               TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false))
                        {
                            //SetDocStatusOnActionDetails("Approved");
                            //SetUserProfiles();
                        }
                        lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                    }
                }
                else
                {

                    //lblError.Text = "Can't be send back. User is not available";
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H4>Personnel Action Clearance form approval is in progress</H4></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                    lop.Begin();
                    if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                               TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false))
                    {
                        //SetDocStatusOnActionDetails("Approved");
                        //SetUserProfiles();
                    }

                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
            }
        }


        /// <summary>
        /// Set document status on Personnel Action Details list.
        /// Used to retrieve the datas for another list (salary Advance Forms)
        /// </summary>
        private void SetDocStatusOnActionDetails(string docStatus)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        string refNo = Request.QueryString["RefID"];
                        camlQry = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                        SPListItemCollection oColl = obj.GetSPListItems(SiteURL, ActionDetails, camlQry);
                        if (oColl != null && oColl.Count > 0)
                        {
                            foreach (SPListItem oItem in oColl)
                            {
                                oItem["Document_x0020_Status"] = docStatus;
                                oWeb.AllowUnsafeUpdates = true;
                                oItem.Update();
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        }
                    }
                }

            });
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation lop = new SPLongOperation(this.Page);
                lop.LeadingHTML = "<DIV><H4>Personnel Action Clearance form rejection in progress</H4></DIV>";
                lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                lop.Begin();

                //string formID = null;// Request.QueryString["FormID"];
                string refNo = Request.QueryString["RefID"];
                string TaskItemID = Request.QueryString["TaskItemID"];

                try
                {
                    SPFieldUserValue userValue = obj.GetSubmittedUser(SiteURL, lstGuid, refNo);
                    trigWFClass.RejectTask(SiteURL, Request.QueryString["TaskItemID"], TaskLstName, MainLstName, Request.QueryString["RefID"]);

                    if (!string.IsNullOrEmpty(upfile.FileName))
                        demandVoucherclass.AddAttachement(SiteURL, AttLibName, refNo, lstGuid, upfile);
                    // Reject user and comments updation
                    string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                    obj.SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, CurrentUser, TxtComments.Text, 0);
                    SetDocStatusOnActionDetails("Rejected");

                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty form" + " :: " + "Parent" + " :: " + "Reject";
                    obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

                lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

            }
        }


        /// <summary>
        /// Get Approver user from task list and check their properties from Workflow Configuration List
        /// Based upon the properties the buttons and radio button should be shown in the screen.
        /// Also bind Submitted details from Master List
        /// </summary>
        public void FormApprovalLoad()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (!string.IsNullOrEmpty(TaskItemID))
                    {
                        using (SPSite FrmSite = new SPSite(SiteURL))
                        {
                            using (SPWeb frmweb = FrmSite.OpenWeb())
                            {
                                SPQuery updatecamQ = new SPQuery();
                                updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                if (frmweb.Lists.TryGetList(TaskLstName) != null)
                                {
                                    SPListItemCollection oitemcoll = frmweb.Lists.TryGetList(TaskLstName).GetItems(updatecamQ);
                                    if (oitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = oitemcoll[0];
                                        WFCurrentOrder = Convert.ToString(oitm["WFCurrentOrder"]);
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        if (WFTaskType == "Dynamic")
                                        {
                                            pnlForward.Visible = true;
                                        }
                                        RadioButtionListvisibility(frmweb, WFTaskType, false, "", Convert.ToInt32(WFCurrentOrder));
                                    }
                                }
                            }
                        }
                    }

                    ReLoadDetails();

                    //ControlsReadOnly();
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "FormApprovalLoad";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Radio button visibility for dynamic users
        /// </summary>
        /// <param name="tasktype"></param>
        /// <param name="optional"></param>
        /// <param name="OptionalUserName"></param>

        public void RadioButtionListvisibility(SPWeb oweb, string tasktype, bool optional, string OptionalUserName, int WFOrder)
        {
            try
            {
                if (Request.QueryString["Mode"] == "New")
                {
                    pnlForward.Visible = false;
                }
                else if (Request.QueryString["Mode"] == "Edit")
                {
                    if (tasktype == "Static")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "Dynamic")
                    {
                        setRadioButtonVisibilityforDynamicType(WFOrder);
                    }
                    else if (tasktype == "UP Attribute")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "EC (Externally Configured)")
                    {
                        pnlForward.Visible = false;
                    }

                    buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                    if (buttonVisibilty[3] == "True")
                    {
                        btnApprove.Visible = true;
                        btnReject.Visible = true;
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnApprove.Visible = false;
                        btnReject.Visible = false;
                        btnSubmit.Visible = true;
                    }
                    if (buttonVisibilty[4] == "False")
                    {
                        pnlCommentArea.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "RadioButtionListvisibility";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        /// <summary>
        /// set radion buttons visibilty for the dynamic work flow users
        /// </summary>
        /// <param name="WFOrder"></param>

        public void setRadioButtonVisibilityforDynamicType(int WFOrder)
        {
            try
            {
                buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                if (buttonVisibilty[0] == "True")
                {
                    rtbSendBack.Visible = true;
                    rtbSendBack.Checked = true;
                }
                else
                {
                    rtbSendBack.Visible = false;
                }
                if (buttonVisibilty[1] == "True")
                {
                    rtbForwardOthers.Visible = true;
                }
                else
                {
                    rtbForwardOthers.Visible = false;
                }

                if (buttonVisibilty[2] == "True")
                {
                    rtbForward.Visible = true;
                }
                else
                {
                    rtbForward.Visible = false;
                }
                if (buttonVisibilty[0] == "False" && buttonVisibilty[1] == "False" && buttonVisibilty[2] == "False")
                {
                    pnlForward.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "setRadioButtonVisibilityforDynamicType";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                if (refID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";

                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {

                    lblActReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtReqDate.SelectedDate = Convert.ToDateTime(lstDatas["RequestDate"]);

                    lstGuid = lstDatas.ParentList.ID.ToString();

                    SetValuesToControls(lstDatas);

                    Label lblreferenceNumber = PersonnelComments.FindControl("lblReferenceNumber") as Label;
                    Label lblSiteUrl = PersonnelComments.FindControl("lblSiteUrl") as Label;
                    Label lblfrmListName = PersonnelComments.FindControl("lblfrmListName") as Label;
                    Label lbldocumentypesList = PersonnelComments.FindControl("lbldocumentTypes") as Label;
                    Label lblCommentsList = PersonnelComments.FindControl("lblCommentsList") as Label;
                    Label lblTaskList = PersonnelComments.FindControl("lblTaskList") as Label;

                    lblTaskList.Text = TaskLstName;
                    lblCommentsList.Text = CmntsLstName;
                    lblfrmListName.Text = MainLstName;
                    lbldocumentypesList.Text = DocumentTypesList;
                    lblreferenceNumber.Text = lblActReqNo.Text;
                    lblSiteUrl.Text = SiteURL;

                    //SetStatusAndClassification();

                    SetStatusAndClassification(ActionType);

                    if (gvSalaryInfo.Rows.Count > 0)

                        SetFooterValues();
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        private void SetValuesToControls(SPListItem lstDatas)
        {
            ArrayList _arrayList;
            txtName.Text = Convert.ToString(lstDatas["Name"]); txtName.ReadOnly = true;

            if (Mode != "New")
            {
                SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, Convert.ToString(lstDatas["SubmittedFor"]));
                PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                _pickerEntity.Key = fldUser.LookupValue;
                _pickerEntity.IsResolved = true;
                _arrayList = new ArrayList();
                _arrayList.Add(_pickerEntity);
                pplActUser.UpdateEntities(_arrayList);
                pplActUser.Enabled = false;

                ddlActionType.SelectedItem.Text = Convert.ToString(lstDatas["ActionType"]);
                ddlActionType.SelectedItem.Selected = true;
            }
            ddlNationality.SelectedItem.Text = Convert.ToString(lstDatas["Nationality"]);
            ddlNationality.SelectedItem.Selected = true; ddlNationality.Enabled = false;

            txtEmployeeNo.Text = Convert.ToString(lstDatas["EmployeeID"]); txtEmployeeNo.ReadOnly = true;
            dtDOB.SelectedDate = Convert.ToDateTime(lstDatas["DOB"]); dtDOB.Enabled = false;

            ddlMaritalStatus.SelectedItem.Text = Convert.ToString(lstDatas["MaritalStatus"]);
            ddlMaritalStatus.SelectedItem.Selected = true; ddlMaritalStatus.Enabled = false;

            txtFathersName.Text = Convert.ToString(lstDatas["FathersName"]); txtFathersName.ReadOnly = true;
            txtNoDependant.Text = Convert.ToString(lstDatas["NoDependants"]); txtNoDependant.ReadOnly = true;
            txtAddress.Text = Convert.ToString(lstDatas["Address"]); txtAddress.ReadOnly = true;
            txtTelNo.Text = Convert.ToString(lstDatas["MobileNo"]); txtTelNo.ReadOnly = true;
            txtPassportNo.Text = Convert.ToString(lstDatas["PassportNo"]); txtPassportNo.ReadOnly = true;
            dtPassValidity.SelectedDate = Convert.ToDateTime(lstDatas["PassportExpiryOn"]); dtPassValidity.Enabled = false;
            dtDOE.SelectedDate = Convert.ToDateTime(lstDatas["DateofEmployment"]); dtDOE.Enabled = false;
            txtQadarID.Text = Convert.ToString(lstDatas["QatarID"]); txtQadarID.ReadOnly = true;
            dtValofResPermit.SelectedDate = Convert.ToDateTime(lstDatas["ResidentPermitValidity"]); dtValofResPermit.Enabled = false;

            if (Mode != "New")
            {
                ddlActionType.SelectedItem.Text = Convert.ToString(lstDatas["ActionType"]);
                ddlActionType.SelectedItem.Selected = true; ddlActionType.Enabled = false;
                ActionType = Convert.ToString(lstDatas["ActionType"]);
            }

            if (ActionType == "Others")
                txtOthers.Text = Convert.ToString(lstDatas["ActionOthers"]);
            if (ActionType == "Appointment")
                pnlDiv.Visible = false;
            else
                pnlDiv.Visible = true;

        }


        #region "DataBind in 2nd Grid"

        //private void SetStatusAndClassification()
        //{

        //    SPSecurity.RunWithElevatedPrivileges(delegate()
        //    {
        //        using (SPSite oSite = new SPSite(SiteURL))
        //        {
        //            using (SPWeb oWeb = oSite.OpenWeb())
        //            {
        //                if (refID != null)
        //                    camlQry = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";

        //                oItemsColl = obj.GetSPListItems(SiteURL, ActionDetails, camlQry);
        //                if (oItemsColl != null)
        //                {
        //                    if (oItemsColl.Count > 0)
        //                    {
        //                        int i = 1;

        //                        DataTable dt = new DataTable();
        //                        DataRow dr = null;
        //                        dt.Columns.Add(new System.Data.DataColumn("Class", typeof(string)));
        //                        dt.Columns.Add(new System.Data.DataColumn("Previous", typeof(string)));
        //                        dt.Columns.Add(new System.Data.DataColumn("Present", typeof(string)));


        //                        foreach (SPListItem oItems in oItemsColl)
        //                        {
        //                            if (Convert.ToString(oItems["Specification"]) == "Designation")
        //                            {
        //                                ddlDesigPrev.SelectedItem.Text = Convert.ToString(oItems["Previous"]); ddlDesigPrev.SelectedItem.Selected = true; ddlDesigPrev.Enabled = false;
        //                                ddlDesigPres.SelectedItem.Text = Convert.ToString(oItems["Present"]); ddlDesigPres.SelectedItem.Selected = true; ddlDesigPres.Enabled = false;
        //                            }
        //                            else if (Convert.ToString(oItems["Specification"]) == "Division")
        //                            {
        //                                ddlDivPrev.SelectedItem.Text = Convert.ToString(oItems["Previous"]); ddlDivPrev.SelectedItem.Selected = true; ddlDivPrev.Enabled = false;
        //                                ddlDivPres.SelectedItem.Text = Convert.ToString(oItems["Present"]); ddlDivPres.SelectedItem.Selected = true; ddlDivPres.Enabled = false;
        //                            }

        //                            else
        //                            {

        //                                if (ViewState["CurrentTable"] == null)
        //                                {

        //                                    dr = dt.NewRow();
        //                                    dr["Class"] = Convert.ToString(oItems["Specification"]);
        //                                    dr["Previous"] = Convert.ToString(oItems["Present"]);
        //                                    dr["Present"] = Convert.ToString(oItems["Present"]);
        //                                    PrevgrdTotal = PrevgrdTotal + Convert.ToDecimal(oItems["Present"]);
        //                                    PresgrdTotal = PresgrdTotal + Convert.ToDecimal(oItems["Present"]);
        //                                    dt.Rows.Add(dr);

        //                                }

        //                            }
        //                        }
        //                        GridView1.DataSource = dt;
        //                        GridView1.DataBind();
        //                        ViewState["CurrentTable"] = dt;

        //                    }
        //                }
        //                else
        //                {

        //                }
        //            }
        //        }
        //    });

        //} 

        #endregion

        private void SetStatusAndClassification(string ActionType)
        {
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            //if (refID != null) 21-05-2013

                            PickerEntity pe = (PickerEntity)pplActUser.Entities[0];
                            string ActUser = pe.DisplayText;

                            camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + ActUser + "</Value>" +
                                "</Eq><IsNull><FieldRef Name=\"Specification\" /></IsNull></And></Where>";
                            oItemsColl = obj.GetSPListItems(SiteURL, ActionDetails, camlQry);
                            if (oItemsColl != null)
                            {
                                if (oItemsColl.Count > 0)
                                {
                                    fnShowDropdownDetails(oItemsColl);
                                }
                            }

                            //if (refID != null) 21-05-2013
                            camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + ActUser + "</Value>" +
                                "</Eq><IsNotNull><FieldRef Name=\"Specification\" /></IsNotNull></And></Where>";
                            oItemsColl = obj.GetSPListItems(SiteURL, ActionDetails, camlQry);
                            if (oItemsColl != null)
                            {
                                if (oItemsColl.Count > 0)
                                {
                                    fnShowGridDetails(oItemsColl);
                                }
                            }
                        }
                    }
                });
            }
            // }
            catch (Exception)
            {

            }


        }


        #endregion

        /// <summary>
        /// Edit expense details in GridView
        /// </summary>
        /// <param name="oitemcollDraw"></param>
        public void fnShowGridDetails(SPListItemCollection oItemsColl)
        {
            try
            {
                ViewState["CurrentTable"] = null;
                SPFieldLookupValue fldPrev = null;
                SPFieldLookupValue fldPres = null;
                DataTable dt = new DataTable();
                DataRow dr = null;
                dt.Columns.Add(new System.Data.DataColumn("sem", typeof(string)));
                dt = (DataTable)ViewState["CurrentTable"];
                if (oItemsColl.Count > 0)
                {
                    int count = oItemsColl.Count;
                    count -= 1;
                    int inc = 0;
                    if (count == 0)
                    {
                        singlerow();
                    }
                    else
                    {
                        singlerow();
                        dt = (DataTable)ViewState["CurrentTable"];
                        while (inc < count)
                        {
                            dr = dt.NewRow();
                            dt.Rows.InsertAt(dr, 0);
                            gvSalaryInfo.DataSource = dt;
                            gvSalaryInfo.DataBind();
                            inc++;
                        }
                    }
                }

                decimal totValue = 0;

                SPFieldLookupValue ofldSpec = null;

                for (int i = 0; i < oItemsColl.Count; i++)
                {

                    oItems = oItemsColl[i];

                    ofldSpec = new SPFieldLookupValue(Convert.ToString(oItems["Specification"]));

                    if (ofldSpec.LookupValue == null)
                    {
                        // Modified on : 22_05_2013
                        #region "old"

                        //ddlDesigPrev.Items.Clear();
                        //ddlDesigPres.Items.Clear();
                        //ddlDivPrev.Items.Clear();
                        //ddlDivPres.Items.Clear();

                        //GetDesignations();
                        //GetDivisions();

                        //fldPrev = new SPFieldLookupValue(Convert.ToString(oItems["PreviousDesignation"]));

                        //ddlDesigPrev.Items.FindByValue(Convert.ToString(fldPrev.LookupId)).Selected = true;

                        //fldPres = new SPFieldLookupValue(Convert.ToString(oItems["PresentDesignation"]));

                        //ddlDesigPres.Items.FindByValue(Convert.ToString(fldPres.LookupId)).Selected = true;

                        //fldPrev = new SPFieldLookupValue(Convert.ToString(oItems["PreviousDivision"]));
                        //if (fldPrev.LookupValue != null)
                        //{
                        //    ddlDivPrev.Items.FindByValue(Convert.ToString(fldPrev.LookupId)).Selected = true;
                        //}
                        //fldPres = new SPFieldLookupValue(Convert.ToString(oItems["PresentDivision"]));

                        //ddlDivPres.Items.FindByValue(Convert.ToString(fldPres.LookupId)).Selected = true;

                        #endregion
                    }
                    else
                    {
                        DropDownList ddlSpecification = (DropDownList)gvSalaryInfo.Rows[i].FindControl("ddlSpecification");

                        TextBox txtPrevious = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPrevious");
                        TextBox txtPresent = (TextBox)gvSalaryInfo.Rows[i].FindControl("txtPresent");

                        txtPrevious.Text = Convert.ToString(oItems["Previous"]);
                        txtPresent.Text = Convert.ToString(oItems["Present"]);

                        if (!string.IsNullOrEmpty(Convert.ToString(oItems["Specification"])))
                        {
                            ofldSpec = new SPFieldLookupValue(Convert.ToString(oItems["Specification"]));
                            //GetClassifications();

                            BindInDropDown(ActionClassifications, ddlSpecification);
                            ddlSpecification.Items.Insert(0, "Select");

                            if (ddlSpecification.Items.FindByValue(Convert.ToString(ofldSpec.LookupId)) != null)
                                ddlSpecification.Items.FindByValue(Convert.ToString(ofldSpec.LookupId)).Selected = true;

                        }

                        if (Mode != "New")
                        {
                            ddlSpecification.Enabled = false; txtPrevious.ReadOnly = true; txtPresent.ReadOnly = true;
                        }
                    }

                }

            }
            catch (Exception ex)
            {

            }

        }


        public void fnShowDropdownDetails(SPListItemCollection oItemsColl)
        {
            try
            {
                SPFieldLookupValue fldPrev = null;
                SPFieldLookupValue fldPres = null;

                SPFieldLookupValue ofldSpec = null;

                for (int i = 0; i < oItemsColl.Count; i++)
                {

                    oItems = oItemsColl[i];

                    ofldSpec = new SPFieldLookupValue(Convert.ToString(oItems["Specification"]));

                    if (ofldSpec.LookupValue == null)
                    {
                        ddlDesigPrev.Items.Clear();
                        ddlDesigPres.Items.Clear();
                        ddlDivPrev.Items.Clear();
                        ddlDivPres.Items.Clear();

                        GetDesignations();
                        GetDivisions();

                        fldPrev = new SPFieldLookupValue(Convert.ToString(oItems["PreviousDesignation"]));

                        ddlDesigPrev.Items.FindByValue(Convert.ToString(fldPrev.LookupId)).Selected = true;

                        fldPres = new SPFieldLookupValue(Convert.ToString(oItems["PresentDesignation"]));

                        ddlDesigPres.Items.FindByValue(Convert.ToString(fldPres.LookupId)).Selected = true;

                        fldPrev = new SPFieldLookupValue(Convert.ToString(oItems["PreviousDivision"]));
                        fldPres = new SPFieldLookupValue(Convert.ToString(oItems["PresentDivision"]));

                        if (fldPrev.LookupValue != null)
                            ddlDivPrev.Items.FindByValue(Convert.ToString(fldPrev.LookupId)).Selected = true;
                        else
                            ddlDivPrev.Items.FindByValue(Convert.ToString(fldPres.LookupId)).Selected = true;

                        ddlDivPres.Items.FindByValue(Convert.ToString(fldPres.LookupId)).Selected = true;
                    }

                    if (Mode != "New")
                    {
                        ddlDesigPrev.Enabled = false; ddlDesigPres.Enabled = false; ddlDivPrev.Enabled = false; ddlDivPres.Enabled = false;
                    }
                }

            }
            catch (Exception ex)
            {

            }

        }


        private void SetUserProfiles()
        {
            string currentUser = SPContext.Current.Web.CurrentUser.ToString().Substring(SPContext.Current.Web.CurrentUser.ToString().IndexOf("\\") + 1);
            SPSite spSite = SPContext.Current.Site;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
                System.Web.HttpContext.Current = null;
                try
                {
                    // Set the context of the site to the SPSite site
                    SPServiceContext context = SPServiceContext.GetContext(spSite);
                    //Create and instance of the UserProfileManager
                    UserProfileManager profileManager = new UserProfileManager(context);
                    UserProfile userProfile = profileManager.GetUserProfile(currentUser);

                    userProfile["PreferredName"].Value = Convert.ToString(txtName.Text);
                    //userProfile["Nationality"].Value = Convert.ToString(ddlNationality.SelectedItem.Text);
                    //userProfile["EmployeeID"].Value = Convert.ToString(txtEmployeeNo.Text);
                    //userProfile["DOB"].Value = Convert.ToString(dtDOB.SelectedDate.Date);
                    //userProfile["CellPhone"].Value = Convert.ToString(txtTelNo.Text);
                    //userProfile["PassportNo"].Value = Convert.ToString(txtEmployeeNo.Text);
                    //userProfile["PassportExpireOn"].Value = Convert.ToString(dtPassValidity.SelectedDate.Date);
                    //userProfile["DOJ"].Value = Convert.ToString(dtDOE.SelectedDate.Date);
                    // userProfile["QatarID"].Value = Convert.ToString(txtEmployeeNo.Text);

                    userProfile.Commit();

                }
                catch (SPException ex)
                {
                }
                finally
                {
                    System.Web.HttpContext.Current = currentContext;
                }

            });

        }


        //private void GetPersonnelActionForm()
        //{
        //    string empId = string.Empty;
        //    if (rdBtn.SelectedIndex == 0)
        //    {
        //        Label lblEmpID = userInfo.FindControl("lblEmpID") as Label;
        //        if (lblEmpID.Text != null)
        //        {
        //            UserProfile up = obj.GetUserInfo(SPContext.Current.Web.CurrentUser.LoginName);
        //            empId = (string)up["EmployeeID"].Value;
        //        }
        //        else
        //        {
        //            empId = lblEmpID.Text;
        //        }
        //    }
        //    else
        //    {
        //        empId = txtReqEmpId.Text;
        //    }
        //    using (SPSite oSite = new SPSite(SiteURL))
        //    {
        //        using (SPWeb oWeb = oSite.OpenWeb())
        //        {
        //            qry = new SPQuery();
        //            camlQry = "<Where><Eq><FieldRef Name=\"EmployeeID\" /><Value Type=\"Text\">" + empId + "</Value></Eq></Where>";
        //            qry.Query = camlQry;
        //            oItem = obj.GetSPListItem(SiteURL, "Personnel Action Forms", qry);
        //            if (oItem != null)
        //            {
        //                dtDOE.SelectedDate = Convert.ToDateTime(oItem["DOB"]);
        //                qry = new SPQuery();
        //                camlQry = "<Where><And><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + Convert.ToString(oItem["Title"]) + "</Value>" +
        //                    "</Eq><Eq><FieldRef Name=\"Specification\" /><Value Type=\"Text\">Basic Salary</Value></Eq></And></Where>";
        //                qry.Query = camlQry;
        //                oItem = obj.GetSPListItem(SiteURL, "Personnel Action Details", qry);
        //                if (oItem != null)
        //                {
        //                    txtBasicSalary.Text = Convert.ToString(oItem["Present"]);
        //                }
        //            }
        //        }
        //    }
        //}


        private void InvisibleButtons()
        {
            btnCntrls.Visible = false;
            pnlView.Visible = true;
            btnSubmit.Visible = false;
            btnApprove.Visible = false;
            btnReject.Visible = false;
            pnlForward.Visible = false;
            pnlCommentArea.Visible = false;
            upAtt.Visible = false;
            btnCancel.Value = "Close";
        }

    }
}
